import { Request } from "express";

import { ArgumentsHost, ExceptionFilter, Catch } from "@nestjs/common";

import { RestDto } from "qqlx-core";
import { parseErrorMessage } from "qqlx-cdk";

import { Logger } from "../lib/log";

@Catch()
export class CommonExceptionFilter implements ExceptionFilter {
  constructor() {}

  catch(_e: any, host: ArgumentsHost) {
    const _ctx = host.switchToHttp();
    const _req = _ctx.getRequest<Request>();
    const _res = _ctx.getResponse();

    // 追踪信息
    const traceId = (_req.body?.dto as RestDto)?.traceInfo?.traceId || _req.header("qqlx-trace-id") || "";
    const traceIp = _req.header("qqlx-trace-ip") || "";

    // 请求体
    const { visitorId, visitorType } = _req.body || {};

    // 记录错误时的请求内容
    const rest: RestDto = {
      traceInfo: { traceId, traceIp, action: `❌ ${_req.method}`, path: _req.path },
      visitorId,
      visitorType,
    };
    Logger.error({ rest, log: `错误明细（From ${(_e as Error)?.stack}）`, detail: _e as any });
    Logger.error({ rest, log: "请求体", detail: { body: _req.body } });

    // 返回请求结果
    _res.json(parseErrorMessage(_e));
  }
}
